package delete

import (
	"gitee.com/zy_blue7/go-gorm-learn/insert"
	"gorm.io/gorm"
)

func Delete(db *gorm.DB) {

	//删除一条记录时，删除对象需要指定主键，否则会触发 批量 Delete，例如：
	user := insert.User{}
	db.Debug().First(&user)
	// 逻辑删除 todo 如果没有 deleted_at 字段， 就是delete 删除语句
	// [rows:1] UPDATE `users` SET `deleted_at`='2022-09-20 16:59:51.337' WHERE `users`.`id` = 1 AND `users`.`deleted_at` IS NULL
	db.Debug().Delete(&user)

	// 带条件带删除
	// UPDATE `users` SET `deleted_at`='2022-09-20 17:02:04.773' WHERE age = 18  AND `users`.`id` = 2 AND `users`.`deleted_at` IS NULL
	db.Debug().Where("age = 18 ").Delete(&user)

	// UPDATE `users` SET `deleted_at`='2022-09-20 17:06:18.849' WHERE `users`.`id` = 10 AND `users`.`deleted_at` IS NULL
	db.Debug().Delete(&insert.User{}, 10)
	// DELETE FROM users WHERE id = 10;

	//db.Delete(insert.User{}, "10")
	// DELETE FROM users WHERE id = 10;

	var users []insert.User
	//  UPDATE `users` SET `deleted_at`='2022-09-20 17:06:18.854' WHERE `users`.`id` IN (1,2,3) AND `users`.`deleted_at` IS NULL
	db.Debug().Delete(&users, []int{1, 2, 3})
	// DELETE FROM users WHERE id IN (1,2,3);

	// --------------批量删除
	db.Where("email LIKE ?", "%jinzhu%").Delete(&insert.User{})
	// DELETE from emails where email LIKE "%jinzhu%";

	db.Delete(&insert.User{}, "email LIKE ?", "%jinzhu%")
	// DELETE from emails where email LIKE "%jinzhu%";
}

/**

todo 返回删除行的数据

返回被删除的数据，仅适用于支持 Returning 的数据库，例如：

// 返回所有列
var users []User
DB.Clauses(clause.Returning{}).Where("role = ?", "admin").Delete(&users)
// DELETE FROM `users` WHERE role = "admin" RETURNING *
// users => []User{{ID: 1, Name: "jinzhu", Role: "admin", Salary: 100}, {ID: 2, Name: "jinzhu.2", Role: "admin", Salary: 1000}}

// 返回指定的列
DB.Clauses(clause.Returning{Columns: []clause.Column{{Name: "name"}, {Name: "salary"}}}).Where("role = ?", "admin").Delete(&users)
// DELETE FROM `users` WHERE role = "admin" RETURNING `name`, `salary`
// users => []User{{ID: 0, Name: "jinzhu", Role: "", Salary: 100}, {ID: 0, Name: "jinzhu.2", Role: "", Salary: 1000}}

*/
